package com.shiro.demo.project.system.login.controllers;

import com.shiro.demo.common.LoginConstants;
import com.shiro.demo.common.LoginLogUtils;
import com.shiro.demo.common.ShiroUtils;
import com.shiro.demo.framework.web.domains.AjaxResult;
import com.shiro.demo.framework.captcha.Constants;
import com.shiro.demo.project.system.login.domain._User;
import com.shiro.demo.project.system.login.services.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/")
public class LoginRegisterController {
    @Autowired
    IAccountService accountService;

    @GetMapping("/login")
    public String login(Model model){
        model.addAttribute("user", new _User());
        return "/login";
    }

    /**
     * 检查登陆结果
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(HttpServletRequest request, Model model) throws Exception{

        if(!StringUtils.isEmpty(request.getAttribute(Constants.CAPTCHA_AUTH_FAILED))){
            throw new Exception("验证码不正确");
        }
        if(request.getAttribute("shiroLoginFailure") != null) {
            throw new Exception("用户名或密码不正确");
        }
        LoginLogUtils.log(ShiroUtils.getUsername(), LoginConstants.LOGIN_SUCCESS, "sdfsd");

        return AjaxResult.success("登陆成功");
    }

    @GetMapping("/register")
    public String register(Model model){
        model.addAttribute("user", new _User());
        return "/register";
    }
    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(_User user) throws Exception{
        try {
            accountService.register(user);
        } catch (Exception e) {
            throw new Exception("注册失败", e);
        }

        return AjaxResult.success("注册成功");
    }

    /**
     * 检查用户名的唯一性
     * @param userName
     * @return
     */
    @PostMapping("/checkUsernameUnique")
    @ResponseBody
    public boolean checkUsernameUnique(@RequestParam("username") String userName){
        return accountService.countOfUserName(userName) == 0;
    }
}
